package com.zyzd.baseprojectofvolly.utils.volley;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by 91986 on 2016/7/25.
 */
public class GsonRequest<T> extends Request<T> {
    public Gson mGson;
    public Class<T> mClazz;
    public Response.Listener mListener;
    Map<String, String> mParams;

    public GsonRequest(int method, String url, Map<String, String> params, Class<T> clazz, Response.Listener listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        mGson = new Gson();
        mClazz = clazz;
        mListener = listener;
        mParams = params;
    }

    /**
     * get请求
     */
    public GsonRequest(String url, Class<T> clazz, Response.Listener listener, Response.ErrorListener errorListener) {
        this(Method.GET, url, null, clazz, listener, errorListener);
    }

    /**
     * post请求
     */
    public GsonRequest(String url, Map<String, String> params, Class<T> clazz, Response.Listener listener, Response.ErrorListener errorListener) {
        this(Method.POST, url, params, clazz, listener, errorListener);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {

        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, "utf-8"));
            //JsonObjectRequest  return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
            //JsonArrayRequest   return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response));
            return Response.success(mGson.fromJson(jsonString, mClazz), HttpHeaderParser.parseCacheHeaders(response));

        } catch (UnsupportedEncodingException e) {
            // e.printStackTrace();
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);
    }

//    @Override
//    public byte[] getBody() throws AuthFailureError {
//        return super.getBody();
//    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mParams;
    }

}
